﻿using System.Dynamic;
using System.Reflection;

namespace TrackSystem.Entities.DataShaping
{
    public class DataShaper<T>
    {
        private readonly List<PropertyInfo> _requriedProperties = [];

        public DataShaper(string fieldsString)
        {
            var properties = typeof(T).GetProperties(
                BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
            if (string.IsNullOrWhiteSpace(fieldsString))
            {
                _requriedProperties = properties.ToList();
            }
            else
            {
                var fields = fieldsString.Split(',', StringSplitOptions.RemoveEmptyEntries);
                foreach (var field in fields)
                {
                    var property = properties.FirstOrDefault(
                        p => p.Name.Equals(field.Trim(), StringComparison.InvariantCultureIgnoreCase));
                    if (property != null)
                    {
                        _requriedProperties.Add(property);
                    }
                }
            }
        }

        public ExpandoObject FetchData(T sourceData)
        {
            var shapedObject = new ExpandoObject();
            foreach(var property in _requriedProperties)
            {
                var propertyValue = property.GetValue(sourceData);
                (shapedObject as IDictionary<string, object>).Add(property.Name, propertyValue);
            }

            return shapedObject;
        }

        public IEnumerable<ExpandoObject> FetchData(IEnumerable<T> sourceData)
        {
            var shapedData = new List<ExpandoObject>();
            foreach (var item in sourceData)
            {
                shapedData.Add(FetchData(item));
            }
            return shapedData;
        }
    }
}
